package com.zhengshang.api.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.zhengshang.api.domain.*;
import com.zhengshang.api.mapper.AppBillRecordMapper;
import com.zhengshang.api.service.IAppBillProductService;
import com.zhengshang.api.service.IAppBillRecordService;
import com.zhengshang.api.service.IAppBillRefundRecordService;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.pay.alipay.AlipayService;
import com.zhengshang.common.pay.wxpay.WxPayUtils;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import com.zhengshang.system.mapper.SysUserMapper;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysDictDataService;
import com.zhengshang.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhengshang.api.mapper.AppPayRecordMapper;
import com.zhengshang.api.service.IAppPayRecordService;
import org.springframework.transaction.annotation.Transactional;

/**
 * APP交易记录Service业务层处理
 *
 * @author zhengshang
 * @date 2021-03-29
 */
@Service
public class AppPayRecordServiceImpl implements IAppPayRecordService {
    @Autowired
    private AppPayRecordMapper appPayRecordMapper;
    @Autowired
    private AppBillRecordMapper appBillRecordMapper;
    @Autowired
    private AlipayService alipayService;

    @Autowired
    private IAppBillRefundRecordService appBillRefundRecordService;
    @Autowired
    private IAppBillRecordService appBillRecordService;
    @Autowired
    private IAppBillProductService appBillProductService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysConfigService configService;


    /**
     * 查询APP交易记录
     *
     * @param recordId APP交易记录ID
     * @return APP交易记录
     */
    @Override
    public AppPayRecord selectAppPayRecordById(Long recordId) {
        return appPayRecordMapper.selectAppPayRecordById(recordId);
    }

    @Override
    public AppPayRecord selectAppPayRecordByOrderNum(String orderNum) {
        return appPayRecordMapper.selectAppPayRecordByOrderNum(orderNum);
    }

    /**
     * 查询APP交易记录列表
     *
     * @param appPayRecord APP交易记录
     * @return APP交易记录
     */
    @Override
    public List<AppPayRecord> selectAppPayRecordList(AppPayRecord appPayRecord) {
        return appPayRecordMapper.selectAppPayRecordList(appPayRecord);
    }

    /**
     * 新增APP交易记录
     *
     * @param appPayRecord APP交易记录
     * @return 结果
     */
    @Override
    public int insertAppPayRecord(AppPayRecord appPayRecord) {
        if (appPayRecord.getCreateTime() == null) appPayRecord.setCreateTime(DateUtils.getNowDate());
        int row = appPayRecordMapper.insertAppPayRecord(appPayRecord);
        return row;
    }

    /**
     * 修改APP交易记录
     *
     * @param appPayRecord APP交易记录
     * @return 结果
     */
    @Override
    public int updateAppPayRecord(AppPayRecord appPayRecord) {
        appPayRecord.setUpdateTime(DateUtils.getNowDate());
        AppBillRecord billRecord = appBillRecordMapper.selectAppBillRecordByPayId(appPayRecord.getRecordId());

        if (ObjectUtils.isNotEmpty(billRecord)) {
            billRecord.setOrderState("3");
            appBillRecordService.updateAppBillRecord(billRecord);
        }
        return appPayRecordMapper.updateAppPayRecord(appPayRecord);
    }

    /**
     * 修改APP交易记录
     *
     * @param appPayRecord APP交易记录
     * @return 结果
     */
    @Override
    public int updateAppPayRecord2(AppPayRecord appPayRecord) {
        appPayRecord.setUpdateTime(DateUtils.getNowDate());
        AppBillRecord billRecord = appBillRecordMapper.selectAppBillRecordByPayId(appPayRecord.getRecordId());
        Integer productType = billRecord.getProductType();

        String productTypeName = "【话费】";
        if (productType.equals(4)) {
            productTypeName = "【电费】";
        }
        if (productType.equals(5)) {
            productTypeName = "【水费】";
        }
        if (productType.equals(6)) {
            productTypeName = "【燃气费】";
        }
        if (productType.equals(10)) {
            productTypeName = "【油卡】";
        }
        if (ObjectUtils.isNotEmpty(billRecord)) {
            billRecord.setOrderState("3");
            appBillRecordService.updateAppBillRecord(billRecord);
            String open = configService.selectConfigByKey("app.fanli.open");
            if (ObjectUtils.isNotEmpty(open) && open.equals("1")) {
                Long userId = billRecord.getUserId();
                SysUser sysUser = userService.selectUserById(userId);
                if (ObjectUtils.isNotEmpty(sysUser)) {
                    BigDecimal amount = billRecord.getMoney().multiply(new BigDecimal("0.01"));
                    userService.updateTwoUserBalance(sysUser, amount, productTypeName);
                }
            }
        }
        return appPayRecordMapper.updateAppPayRecord(appPayRecord);
    }

    @Override
    public int refund(AppPayRecord appPayRecord) {
        Long recordId = appPayRecord.getRecordId();
        if (ObjectUtils.isNotEmpty(recordId)) {
            appPayRecord = appPayRecordMapper.selectAppPayRecordById(recordId);
            String payType = appPayRecord.getPayType();
            String state = appPayRecord.getStatus();
            if (state.equals("20")) {
                AppBillRecord billRecord = appBillRecordMapper.selectAppBillRecordByPayId(recordId);
                boolean tag=false;
                if (payType.equals("1")) {
                    tag=refund(appPayRecord, billRecord);
                }
                if (payType.equals("2")) {
                    tag=refundByWx(appPayRecord, billRecord);
                }
                if(tag) {
                    //退款
                    appPayRecord.setRechargeState("2");
                    //appPayRecord.setStatus("30");
                    appPayRecordMapper.updateAppPayRecord(appPayRecord);
                    Long userId = appPayRecord.getUserId();
                    AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByPayId(recordId);
                    if (StringUtils.isNotNull(appBillRecord)) {
                        String remark = appBillRecord.getRemark();
                        if (StringUtils.isNotEmpty(remark)) {
                            if (ObjectUtils.isNotEmpty(remark) && (remark.equals("100"))) {
                                //话费
                                SysUser sysUser = userService.selectUserById(userId);
                                Integer couponCount = sysUser.getCouponCount();
                                couponCount = couponCount + 1;
                                if (couponCount <= 2) {
                                    sysUser.setCouponCount(couponCount);
                                    userService.updateUser(sysUser);
                                }
                            }
                        }
                    }
                    appBillRecordService.updateAppBillRecord(billRecord);
                    return 1;
                }
            }
        }
        return 0;
    }

    /**
     * 批量删除APP交易记录
     *
     * @param recordIds 需要删除的APP交易记录ID
     * @return 结果
     */
    @Override
    public int deleteAppPayRecordByIds(Long[] recordIds) {
        return appPayRecordMapper.deleteAppPayRecordByIds(recordIds);
    }

    /**
     * 删除APP交易记录信息
     *
     * @param recordId APP交易记录ID
     * @return 结果
     */
    @Override
    public int deleteAppPayRecordById(Long recordId) {
        return appPayRecordMapper.deleteAppPayRecordById(recordId);
    }

    @Override
    public int cancelOrder(AppPayRecord appPayRecord) {
        return appPayRecordMapper.cancelOrder(appPayRecord);
    }

    @Transactional
    @Override
    public int travelRecharge(AppPayRecord appPayRecord) {
        Map<String, String> param = new HashMap<>();
        param.put("phoneno", appPayRecord.getPhone());
        param.put("cardnum", appPayRecord.getPayMoney().toString());
        param.put("orderid", appPayRecord.getOrderNum());
        param.put("key", AppConstant.JHDATA_TELCHECK_MOBILE_KEY);
        String result = HttpUtils.sendPost(AppConstant.JHDATA_TELCHECK_MOBILE_URL, HttpUtils.getParam(param));
        return 0;
    }

    @Override
    public List<AppPayRecord> queryListOrderby(AppPayRecord appPayRecord) {
        return appPayRecordMapper.queryListOrderby(appPayRecord);
    }

    @Override
    public List<OilcardAppPayRecord> queryOilcardOrderby(AppPayRecord appPayRecord) {
        return appPayRecordMapper.queryOilcardOrderby(appPayRecord);
    }

    @Override
    public List<ThirdCloumnAppPayRecord> queryThirdColumnOrderby(AppPayRecord appPayRecord) {
        return appPayRecordMapper.queryThirdColumnOrderby(appPayRecord);
    }

    @Override
    public List<Map> queryThirdColumnOrderList(Map params) {
        return appPayRecordMapper.queryThirdColumnOrderList(params);
    }


    /**
     * 退款
     *
     * @param appPayRecord
     * @param appBillRecord
     */
    public boolean refund(AppPayRecord appPayRecord, AppBillRecord appBillRecord) {
        boolean tag=false;
        try {
            String buyType = appPayRecord.getBuyType();
            String refundOrderNum = appPayRecord.getOrderNum() + "TK";
            String result = alipayService.alipayRefund(appPayRecord.getOrderNum(), appPayRecord.getPayMoney().toString(), "订单退款", refundOrderNum);
            JSONObject object = JSONObject.parseObject(result);
            JSONObject alipayTradeRefundResponse = object.getJSONObject("alipay_trade_refund_response");
            if ("10000".equals(alipayTradeRefundResponse.getString("code"))) {
                //退款记录
                AppBillRefundRecord appBillRefundRecord = new AppBillRefundRecord();
                appBillRefundRecord.setUserId(appBillRecord.getUserId());
                appBillRefundRecord.setBillId(appBillRecord.getRecordId());
                appBillRefundRecord.setOrderNum(appBillRecord.getOrderNum());
                appBillRefundRecord.setRefundOrderNum(refundOrderNum);
                appBillRefundRecord.setRefundType(appPayRecord.getPayType());
                appBillRefundRecord.setRefundFee(appPayRecord.getPayMoney());
                appBillRefundRecord.setTotalFee(appPayRecord.getPayMoney());
                appBillRefundRecord.setResult(result);
                appBillRefundRecord.setCreateBy(appBillRecord.getCreateBy());
                appBillRefundRecordService.insertAppBillRefundRecord(appBillRefundRecord);
                appBillRecord.setRefundTime(DateUtils.getNowDate());
                appBillRecord.setOrderState("5");
                tag= true;
            }

        } catch (Exception e) {
            //appBillRecord.setOrderState("6");
            tag= false;
        }
        return tag;
    }

    /**
     * 退款
     *
     * @param appPayRecord
     */
    private boolean refundByWx(AppPayRecord appPayRecord, AppBillRecord appBillRecord) {
        boolean tag=false;
        try {

            String refundOrderNum = appPayRecord.getOrderNum() + "TK";
            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
//            wxPayRefundRequest.setTransactionId(appPayRecord.getTransactionId());//微信支付订单号
            wxPayRefundRequest.setOutTradeNo(appPayRecord.getOrderNum());//商户订单号
            wxPayRefundRequest.setOutRefundNo(refundOrderNum);//商户退款单号
            int totalFee = appPayRecord.getPayMoney().multiply(new BigDecimal(100)).intValue();
            wxPayRefundRequest.setTotalFee(totalFee);//订单金额
            wxPayRefundRequest.setRefundFee(totalFee);//退款金额
            WxPayRefundResult wxPayRefundResult = WxPayUtils.getWxPayService().refund(wxPayRefundRequest);

            //退款记录
            AppBillRefundRecord appBillRefundRecord = new AppBillRefundRecord();
            appBillRefundRecord.setUserId(appBillRecord.getUserId());
            appBillRefundRecord.setBillId(appBillRecord.getRecordId());
            appBillRefundRecord.setOrderNum(appBillRecord.getOrderNum());
            appBillRefundRecord.setRefundOrderNum(refundOrderNum);
            appBillRefundRecord.setRefundType(appPayRecord.getPayType());
            appBillRefundRecord.setRefundFee(appPayRecord.getPayMoney());
            appBillRefundRecord.setTotalFee(appPayRecord.getPayMoney());
            appBillRefundRecord.setResult(wxPayRefundResult.toString());
            appBillRefundRecord.setCreateBy(appBillRecord.getCreateBy());
            appBillRefundRecordService.insertAppBillRefundRecord(appBillRefundRecord);
            appBillRecord.setRefundTime(DateUtils.getNowDate());
            appBillRecord.setOrderState("5");
            tag=true;
        } catch (Exception e) {
            //appBillRecord.setOrderState("6");
            tag=false;
        }
        return tag;
    }
}